package cmsi.utils;

import com.alibaba.druid.util.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Properties;

/**
 * Created by qiliping on 16/4/2.
 *
 */
public class WxInterceptor implements HandlerInterceptor {
    private static Logger log = Logger.getLogger(WxInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**判断页面浏览器*/
        String userAgent = request.getHeader("User-Agent");
        log.info(userAgent+"访问"+request.getRequestURL());

        if (request.getRequestURL().indexOf("login") > 0 ) {
            return true;
        }

        if (request.getRequestURL().indexOf("wx_in") > 0 ) {
            return true;
        }

        Subject currentUser = SecurityUtils.getSubject();//获取当前用户

        if (userAgent.indexOf("MicroMessenger") > 0) {

            if (!currentUser.isAuthenticated()) {
                Properties properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
                String wxLoginUrl = properties.getProperty("wxLoginUrl");
                String wxAPPID = properties.getProperty("wxAPPID");
//                String wxAPPSECRET = properties.getProperty("wxAPPSECRET");

                /**跳转到微信授权页面*/
                String targetUrl = request.getRequestURL().toString();
                if(StringUtils.isEmpty(request.getQueryString())==false){
                    targetUrl += "?"+request.getQueryString();
                }

                if(targetUrl.indexOf("wx_in")>0){
                    targetUrl = "";
                }
                String redirectUri = wxLoginUrl+"?target_url="+targetUrl;

                String login_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + wxAPPID +
                        "&redirect_uri=" + URLEncoder.encode(redirectUri, "utf-8").toString() +
                        "&response_type=code" +
                        "&scope=snsapi_userinfo" +
                        "&state=STATE" +
                        "&connect_redirect=1#wechat_redirect";
//                return "redirect:"+login_url;

                response.sendRedirect(login_url);
                return false;
            } else {
                return true;
            }
        }
        /*else {
            if (!currentUser.isAuthenticated()) {
                *//**跳转到登录页面*//*
                response.sendRedirect("login");
                return false;
            } else {
                return true;
            }
        }*/
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.indexOf("MicroMessenger") > 0) {
            if(userAgent.indexOf("iPhone")>0) {
                /**iPhone 微信浏览器*/
                modelAndView.addObject("userAgent","MicroMessenger-iphone");
            }else if(userAgent.indexOf("android")>0){
                /**Android 微信浏览器*/
                modelAndView.addObject("userAgent","MicroMessenger-android");
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
